import Router from 'koa-router';
import { SysAdminService } from '../../service/system/SysAdmin.js';
import {
  CreateSysAdminDto,
  UpdateSysAdminDto,
  SysAdminQueryDto,
} from '../../entities/system/SysAdmin.js';
import type { AppContext } from '../../types/index.js';
import { Response } from '../../utils/response.js';
import { BusinessException } from '../../types/exceptions.js';
import { ValidationUtil } from '../../utils/validation.js';

const router = new Router<Record<string, unknown>, AppContext>();

/**
 * 管理员控制器
 * @description 使用单例模式，避免重复创建服务实例
 */
class AdminController {
  private static instance: AdminController;
  private readonly adminService: SysAdminService;

  private constructor() {
    this.adminService = new SysAdminService();
  }

  static getInstance(): AdminController {
    if (!AdminController.instance) {
      AdminController.instance = new AdminController();
    }
    return AdminController.instance;
  }

  /**
   * 创建管理员
   * @param ctx 应用上下文
   */
  async create(ctx: AppContext): Promise<void> {
    const admin = ctx.request.body as CreateSysAdminDto;

    // 参数验证
    ValidationUtil.validateRequiredString(admin.admin_name as string, '用户名');
    ValidationUtil.validateRequiredString(admin.password as string, '密码');
    ValidationUtil.validateRequiredString(admin.nick_name as string, '昵称');

    const adminId = await this.adminService.create(admin);
    ctx.body = Response.success('创建成功', { id: adminId });
  }

  /**
   * 获取管理员列表
   * @param ctx 应用上下文
   */
  async list(ctx: AppContext): Promise<void> {
    const { page, pageSize, ...query } = ctx.query;
    const { pageNum, pageSizeNum } = ValidationUtil.validatePagination(
      page as string,
      pageSize as string
    );

    const result = await this.adminService.list(pageNum, pageSizeNum, query as SysAdminQueryDto);
    ctx.body = Response.pagination('查询成功', result);
  }

  /**
   * 更新管理员信息
   * @param ctx 应用上下文
   */
  async update(ctx: AppContext): Promise<void> {
    const id = ValidationUtil.validateId(ctx.params.id, '管理员ID');
    const admin = ctx.request.body as UpdateSysAdminDto;

    // 参数验证
    if (admin.admin_name) {
      ValidationUtil.validateRequiredString(admin.admin_name as string, '用户名');
    }
    if (admin.nick_name) {
      ValidationUtil.validateRequiredString(admin.nick_name as string, '昵称');
    }

    const success = await this.adminService.update(id, admin);
    if (!success) {
      throw new BusinessException('用户不存在或已被删除');
    }

    ctx.body = Response.success('更新成功');
  }

  /**
   * 删除管理员
   * @param ctx 应用上下文
   */
  async delete(ctx: AppContext): Promise<void> {
    const id = ValidationUtil.validateId(ctx.params.id, '管理员ID');

    const success = await this.adminService.delete(id);
    if (!success) {
      throw new BusinessException('管理员不存在');
    }

    ctx.body = Response.success('删除成功');
  }

  /**
   * 获取管理员详情
   * @param ctx 应用上下文
   */
  async getById(ctx: AppContext): Promise<void> {
    const id = ValidationUtil.validateId(ctx.params.id, '管理员ID');

    const admin = await this.adminService.getById(id);
    if (!admin) {
      throw new BusinessException('管理员不存在');
    }
    ctx.body = Response.success('获取成功', admin);
  }
}

const controller = AdminController.getInstance();

// 路由定义 - 使用控制器方法
router.post('/create', (ctx: AppContext) => controller.create(ctx));
router.get('/list', (ctx: AppContext) => controller.list(ctx));
router.put('/:id', (ctx: AppContext) => controller.update(ctx));
router.delete('/:id', (ctx: AppContext) => controller.delete(ctx));
router.get('/:id', (ctx: AppContext) => controller.getById(ctx));

export default router;
